
import Food from "./Food";
import ScorePanel from "./ScorePanel";
import Snake from "./Snake";

class GameController {
    food: Food;
    snake: Snake;
    scorePanel: ScorePanel;

    //键盘按下的方向
    dirction: string = '';

    constructor() {
        this.food = new Food();
        this.snake = new Snake();
        this.scorePanel = new ScorePanel();

        this.init();
    }

    init() {
        document.addEventListener('keydown', this.keyDownHandle.bind(this));
        this.run();
    }

    keyDownHandle(e: KeyboardEvent) {
        console.log(e.key);
        this.dirction = e.key;

    }


    run() {
        let X = this.snake.X;
        let Y = this.snake.Y;



        switch (this.dirction) {
            case 'ArrowLeft':
                X -= 10;
                break;
            case 'ArrowRight':
                X += 10;
                break;
            case 'ArrowUp':
                Y -= 10;
                break;
            case 'ArrowDown':
                Y += 10;
                break;
        }
        this.checkEatFood(X,Y);
        

        try {
            this.snake.X = X;
            this.snake.Y = Y;
            setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30);

        } catch (e: any) {

            alert(e.message);
        }

    }

    checkEatFood(x: number, y: number) {
        if(this.food.X==x && this.food.Y==y){
            console.log('吃到食物');

            this.scorePanel.addScore();
            this.food.change();
            this.snake.addBody();
        }
        
         
    }
}

export default GameController;


